package com.xhji.web.mvc.exception;

import com.xhji.web.mvc.response.GenericResponse;
import org.springframework.validation.BindException;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.MethodArgumentNotValidException;

import javax.validation.ConstraintViolationException;
import java.util.Objects;
import java.util.stream.Collectors;

public class ExceptionUtils {
    public static Throwable convertValidateException(Throwable e) {
        if (Objects.isNull(e)) {
            return null;
        } else if (!(e instanceof MethodArgumentNotValidException) && !(e instanceof BindException)) {
            if (e instanceof ConstraintViolationException) {
                ConstraintViolationException exception = (ConstraintViolationException)e;
                return new ValidationException(exception.getConstraintViolations().stream().map((constraintViolation) -> new GenericResponse.FieldError(constraintViolation.getPropertyPath().toString(), constraintViolation.getMessage(), constraintViolation.getInvalidValue())).collect(Collectors.toList()));
            } else {
                return e;
            }
        } else {
            BindingResult bindingResult = null;
            if (e instanceof MethodArgumentNotValidException) {
                bindingResult = ((MethodArgumentNotValidException)e).getBindingResult();
            }

            if (e instanceof BindException) {
                bindingResult = ((BindException)e).getBindingResult();
            }

            return new ValidationException(bindingResult.getFieldErrors().stream().map((fieldError) -> new GenericResponse.FieldError(fieldError.getField(), fieldError.getDefaultMessage(), fieldError.getRejectedValue())).collect(Collectors.toList()));
        }
    }
}
